<?php
// 课室编辑页面 - 完整增强版课室管理功能
// 文件：/workspace/edit_room.php

// 启用错误显示用于调试
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// 启动会话
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

// 检查用户登录
if (!isset($_SESSION['user_id'])) {
    header("Location: index.php");
    exit();
}

// 数据库连接
require_once 'database.php';

// 独立的权限验证函数
function checkUserPermission($user_id, $conn) {
    try {
        $stmt = $conn->prepare("SELECT role FROM user_roles WHERE user_id = ?");
        if (!$stmt) {
            return false;
        }

        $stmt->bind_param("s", $user_id);
        $stmt->execute();
        $result = $stmt->get_result();

        $has_permission = false;
        while ($row = $result->fetch_assoc()) {
            if ($row['role'] === '考试项目管理员') {
                $has_permission = true;
                break;
            }
        }

        $stmt->close();
        return $has_permission;
    } catch (Exception $e) {
        error_log("权限检查失败: " . $e->getMessage());
        return false;
    }
}

// 验证用户权限
$current_user_id = $_SESSION['user_id'];
if (!checkUserPermission($current_user_id, $conn)) {
    $_SESSION['error_message'] = "您没有权限访问此页面。";
    header("Location: user_home.php");
    exit();
}

// 获取课室ID
$room_id = isset($_GET['id']) ? intval($_GET['id']) : 0;
if ($room_id <= 0) {
    $_SESSION['error_message'] = "无效的课室ID";
    header("Location: rooms_display.php");
    exit();
}

// 获取课室信息
$room_data = null;
try {
    $stmt = $conn->prepare("SELECT * FROM examination_rooms WHERE id = ?");
    $stmt->bind_param("i", $room_id);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows > 0) {
        $room_data = $result->fetch_assoc();
    } else {
        $_SESSION['error_message'] = "课室不存在";
        header("Location: rooms_display.php");
        exit();
    }
    $stmt->close();
} catch (Exception $e) {
    $_SESSION['error_message'] = "获取课室信息失败: " . $e->getMessage();
    header("Location: rooms_display.php");
    exit();
}

// 处理POST请求
$success_message = '';
$error_message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $administrator_name = $_POST['administrator_name'] ?? '待填写';
        $purpose = $_POST['purpose'] ?? '考场';
        $ownership = $_POST['ownership'] ?? '华材';
        $capacity = intval($_POST['capacity'] ?? 30);

        // 更新课室信息
        $update_stmt = $conn->prepare("
            UPDATE examination_rooms
            SET administrator_name = ?, purpose = ?, ownership = ?, capacity = ?, updated_at = NOW()
            WHERE id = ?
        ");

        if (!$update_stmt) {
            throw new Exception("数据库更新准备失败: " . $conn->error);
        }

        $update_stmt->bind_param("sssii",
            $administrator_name,
            $purpose,
            $ownership,
            $capacity,
            $room_id
        );

        if ($update_stmt->execute()) {
            $success_message = "课室 {$room_data['room_number']} 更新成功！";
            // 重新获取更新后的数据
            $stmt = $conn->prepare("SELECT * FROM examination_rooms WHERE id = ?");
            $stmt->bind_param("i", $room_id);
            $stmt->execute();
            $result = $stmt->get_result();
            $room_data = $result->fetch_assoc();
            $stmt->close();
        } else {
            throw new Exception("更新课室失败：" . $update_stmt->error);
        }
        $update_stmt->close();

    } catch (Exception $e) {
        error_log("更新课室错误: " . $e->getMessage());
        $error_message = $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>编辑课室 - 考务管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <link rel="stylesheet" href="css/unified-style.css">
    <style>
        .form-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #0d6efd;
        }

        .radio-option {
            margin: 5px;
            padding: 8px 15px;
            font-size: 14px;
            border-radius: 5px;
            background-color: white;
            color: #0d6efd;
            border: 1px solid #0d6efd;
            transition: all 0.3s ease;
        }

        .radio-option.active {
            background-color: #0d6efd;
            border-color: #0d6efd;
            color: white;
        }

        .room-info-display {
            background: #e3f2fd;
            padding: 15px;
            border-radius: 8px;
            margin: 15px 0;
            border: 2px solid #2196f3;
        }

        .room-info-display h5 {
            color: #1976d2;
            margin-bottom: 10px;
        }

        .room-number {
            font-size: 24px;
            font-weight: bold;
            color: #0d47a1;
        }

        .enhancement-notice {
            background: #fff3cd;
            border: 1px solid #ffeaa7;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            color: #856404;
        }

        .enhancement-notice .badge {
            background: #ffc107;
            color: #212529;
            margin-right: 5px;
        }

        .submit-section {
            background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
            padding: 30px;
            border-radius: 12px;
            margin: 30px 0;
            border: 2px solid #dee2e6;
            box-shadow: 0 4px 8px rgba(0,0,0,0.1);
        }

        .submit-section .btn {
            padding: 12px 30px;
            font-size: 16px;
            font-weight: 600;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .submit-section .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.15);
        }
    </style>
</head>
<body>
    <?php
    // 安全包含导航栏
    try {
        include_once 'common/navigation.php';
    } catch (Exception $e) {
        // 如果导航栏包含失败，显示简单的头部
        echo '<nav class="navbar navbar-expand-lg navbar-dark bg-primary">';
        echo '<div class="container-fluid">';
        echo '<a class="navbar-brand" href="user_home.php">🎓 考务管理系统</a>';
        echo '<a class="nav-link text-white" href="user_home.php">返回首页</a>';
        echo '</div>';
        echo '</nav>';
    }
    ?>

    <div class="container mt-4">
        <div class="row">
            <div class="col-12">
                <div class="card shadow">
                    <div class="card-header bg-info text-white">
                        <h4 class="mb-0"><i class="fas fa-edit"></i> 编辑课室 - <?php echo htmlspecialchars($room_data['room_number']); ?></h4>
                    </div>
                    <div class="card-body">

                        <!-- 功能说明通知 -->
                        <div class="enhancement-notice">
                            <h6><i class="fas fa-info-circle"></i> 编辑说明</h6>
                            <p class="mb-0">
                                <span class="badge">EDIT</span>
                                您可以修改课室的管理员信息、用途、归属权和容量。课室号和位置信息不可修改。
                            </p>
                        </div>

                        <?php if ($success_message): ?>
                            <div class="alert alert-success alert-dismissible fade show" role="alert">
                                <i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success_message); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <?php if ($error_message): ?>
                            <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                <i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error_message); ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                            </div>
                        <?php endif; ?>

                        <!-- 课室基本信息展示 -->
                        <div class="room-info-display">
                            <h5><i class="fas fa-info-circle"></i> 课室基本信息</h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="room-number"><?php echo htmlspecialchars($room_data['room_number']); ?></div>
                                    <small class="text-muted">课室号（不可修改）</small>
                                </div>
                                <div class="col-md-6">
                                    <div><strong>类型：</strong><?php echo htmlspecialchars($room_data['room_type']); ?></div>
                                    <div><strong>楼栋：</strong><?php echo htmlspecialchars($room_data['building']); ?></div>
                                    <div><strong>楼层：</strong><?php echo htmlspecialchars($room_data['floor']); ?></div>
                                    <?php if (!empty($room_data['sub_building'])): ?>
                                        <div><strong>区域：</strong><?php echo htmlspecialchars($room_data['sub_building']); ?></div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>

                        <form method="POST" id="editRoomForm">
                            <!-- 管理员信息 -->
                            <div class="form-section">
                                <h5><i class="fas fa-user-tie"></i> 管理员信息</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="administrator_name" class="form-label">班主任姓名/课室管理员姓名</label>
                                        <input type="text" class="form-control" name="administrator_name" id="administrator_name"
                                               value="<?php echo htmlspecialchars($room_data['administrator_name'] ?? '待填写'); ?>">
                                        <div class="form-text">可修改管理员姓名</div>
                                    </div>
                                </div>
                            </div>

                            <!-- 课室用途 -->
                            <div class="form-section">
                                <h5><i class="fas fa-clipboard-list"></i> 课室用途</h5>
                                <div class="row">
                                    <div class="col-12">
                                        <?php
                                        $current_purpose = $room_data['purpose'] ?? '考场';
                                        $purposes = ['考场', '备用考场', '考点办公室', '接待室', '广播室', '医疗室', '教师办公室', '空白'];
                                        foreach ($purposes as $purpose): ?>
                                            <button type="button" class="btn radio-option <?php echo $purpose === $current_purpose ? 'active' : ''; ?>"
                                                    data-value="<?php echo $purpose; ?>"><?php echo $purpose; ?></button>
                                        <?php endforeach; ?>
                                    </div>
                                </div>
                                <input type="hidden" name="purpose" id="purpose" value="<?php echo htmlspecialchars($current_purpose); ?>">
                            </div>

                            <!-- 课室归属权 -->
                            <div class="form-section">
                                <h5><i class="fas fa-certificate"></i> 课室归属权</h5>
                                <?php $current_ownership = $room_data['ownership'] ?? '华材'; ?>
                                <div class="btn-group" role="group">
                                    <button type="button" class="btn radio-option <?php echo $current_ownership === '华材' ? 'active' : ''; ?>"
                                            data-value="华材">华材</button>
                                    <button type="button" class="btn radio-option <?php echo $current_ownership === '技工' ? 'active' : ''; ?>"
                                            data-value="技工">技工</button>
                                </div>
                                <input type="hidden" name="ownership" id="ownership" value="<?php echo htmlspecialchars($current_ownership); ?>">
                            </div>

                            <!-- 课室容量 -->
                            <div class="form-section">
                                <h5><i class="fas fa-users"></i> 课室容量</h5>
                                <div class="row">
                                    <div class="col-md-6">
                                        <label for="capacity" class="form-label">容量（人数）</label>
                                        <input type="number" class="form-control" name="capacity" id="capacity"
                                               value="<?php echo intval($room_data['capacity'] ?? 30); ?>" min="1" max="100">
                                        <div class="form-text">请输入课室最大容纳人数</div>
                                    </div>
                                </div>
                            </div>

                            <!-- 提交按钮 -->
                            <div class="submit-section text-center">
                                <button type="submit" class="btn btn-success btn-lg me-3">
                                    <i class="fas fa-save"></i> 保存修改
                                </button>
                                <a href="rooms_display.php" class="btn btn-warning btn-lg">
                                    <i class="fas fa-arrow-left"></i> 返回课室列表
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // 选择课室用途
        document.querySelectorAll('.radio-option').forEach(btn => {
            btn.addEventListener('click', function() {
                // 只影响同一组的按钮
                const parentSection = this.closest('.form-section');
                parentSection.querySelectorAll('.radio-option').forEach(b => b.classList.remove('active'));
                this.classList.add('active');

                // 更新对应的隐藏字段
                const hiddenInput = parentSection.querySelector('input[type="hidden"]');
                if (hiddenInput) {
                    hiddenInput.value = this.dataset.value;
                }
            });
        });
    </script>
</body>
</html>